﻿/*
   Copyright 2014 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using Flower.Services;
using Flower.Services.Data;
using Jurassic;
using Jurassic.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Flower.Directory.Scripting.Functions.ServiceContainers
{
    internal class GetServiceContainer : ClrFunction
    {
        public GetServiceContainer(ScriptEngine engine)
            : base(engine.Function.InstancePrototype, "__getServiceContainer", engine.Function.InstancePrototype)
        {
        }

        [JSCallFunction]
        public ObjectInstance Exec(string serviceContainerPath, object globalServiceContainers)
        {
            try
            {
                IDirectory dir = Engine.GetDirectory();

                var globalServiceContainersArr = globalServiceContainers as ArrayInstance;
                IList<DirectoryEntry> globalServiceContainersList = null;

                if (globalServiceContainersArr != null)
                {
                    globalServiceContainersList = new List<DirectoryEntry>();

                    foreach (DirectoryEntryObject gsc in globalServiceContainersArr.ElementValues)
                    {
                        globalServiceContainersList.Add(gsc.Entry);
                    }
                }

                var result = Exec(dir, serviceContainerPath, globalServiceContainersList);
                var retval =
                    Engine
                        .Object
                        .Construct();

                object globalServiceContainersListResult;
                if (result.TryGetValue("globalServiceContainers", out globalServiceContainersListResult))
                {
                    globalServiceContainersArr = 
                        Engine
                            .Array
                            .Construct();

                    foreach (DirectoryEntry gsc in (IList<DirectoryEntry>)globalServiceContainersListResult)
                    {
                        globalServiceContainersArr.Push((object)JsConvert.EntryToObject(Engine, gsc));
                    }

                    retval.Set("globalServiceContainers", globalServiceContainersArr);
                }

                object serviceContainer;
                if (result.TryGetValue("serviceContainer", out serviceContainer))
                {
                    retval.Set
                    (
                        "serviceContainer", 
                        JsConvert.EntryToObject(Engine, (DirectoryEntry)serviceContainer)
                    );
                }

                return retval;
            }
            catch (JavaScriptException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new JavaScriptException(Engine, "Error", ex.Message, ex);
            }
        }

        [ClrScript]
        public static Dictionary<string, object> Exec(IDirectory dir, string serviceContainerPath, IList<DirectoryEntry> globalServiceContainers)
        {
            IList<DirectoryEntry> globalServiceContainersResult = null;

            if (globalServiceContainers != null)
            {
                bool loadingRequired = false;

                if (dir.CountChildren("/Services/Flower", DirectoryEntryTypes.ServiceContainer) != globalServiceContainers.Count)
                {
                    loadingRequired = true;
                }
                else
                {
                    foreach (DirectoryEntry gsc in globalServiceContainers)
                    {
                        if
                        (
                            !dir.Exists(gsc.Id, DateTime.MinValue) ||
                            dir.Exists(gsc.Id, gsc.UpdatedOn)
                        )
                        {
                            loadingRequired = true;
                            break;
                        }
                    }
                }

                if (loadingRequired)
                {
                    globalServiceContainersResult =
                        dir.GetChildren("/Services/Flower", DirectoryEntryTypes.ServiceContainer, SortProperty.Default, SortOrder.Asc, 0, long.MaxValue);
                }
            }

            DirectoryEntry serviceContainer = dir.Get(serviceContainerPath);

            var result = new Dictionary<string, object>();

            if (globalServiceContainersResult != null)
            {
                result["globalServiceContainers"] = globalServiceContainersResult;
            }

            if (serviceContainer != null)
            {
                result["serviceContainer"] = serviceContainer;
            }

            return result;
        }
    }
}
